<template>
  <div class="my-videos-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon class="title-icon"><VideoPlay /></el-icon>
          我的视频
        </h1>
        <p class="page-subtitle">管理您上传和点赞的视频内容</p>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Upload /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ uploadedVideos.length }}</div>
            <div class="stat-label">已上传</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Star /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ likedVideos.length }}</div>
            <div class="stat-label">已点赞</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><View /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ totalViews }}</div>
            <div class="stat-label">总播放量</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Star /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ totalLikes }}</div>
            <div class="stat-label">总获赞</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和排序 -->
    <div class="filter-section">
      <div class="filter-container">
        <div class="filter-group">
          <el-select v-model="selectedType" placeholder="选择类型" size="large">
            <el-option label="全部视频" value="all" />
            <el-option label="已上传" value="uploaded" />
            <el-option label="已点赞" value="liked" />
          </el-select>
        </div>
        <div class="filter-group">
          <el-select v-model="sortBy" placeholder="排序方式" size="large">
            <el-option label="最新上传" value="newest" />
            <el-option label="播放量最高" value="views" />
            <el-option label="点赞最多" value="likes" />
            <el-option label="标题A-Z" value="title" />
          </el-select>
        </div>
        <div class="filter-group">
          <el-button-group>
            <el-button 
              :type="viewMode === 'grid' ? 'primary' : 'default'" 
              @click="viewMode = 'grid'"
              size="large"
            >
              <el-icon><Grid /></el-icon>
              网格
            </el-button>
            <el-button 
              :type="viewMode === 'list' ? 'primary' : 'default'" 
              @click="viewMode = 'list'"
              size="large"
            >
              <el-icon><List /></el-icon>
              列表
            </el-button>
          </el-button-group>
        </div>
      </div>
    </div>

    <!-- 视频内容 -->
    <div class="content-section">
      <div class="videos-container" :class="viewMode">
        <div 
          v-for="video in filteredVideos" 
          :key="video.id" 
          class="video-card"
          @click="goToDetail(video.id)"
        >
          <div class="video-thumbnail">
            <img :src="video.thumbnail" :alt="video.title" />
            <div class="video-overlay">
              <el-icon class="play-icon"><CaretRight /></el-icon>
            </div>
            <div class="video-duration">{{ video.duration }}</div>
            <div class="video-status" :class="video.status">
              {{ getStatusText(video.status) }}
            </div>
          </div>
          <div class="video-info">
            <h3 class="video-title">{{ video.title }}</h3>
            <p class="video-description">{{ video.description }}</p>
            <div class="video-meta">
              <div class="meta-left">
                <span class="views">
                  <el-icon><View /></el-icon>
                  {{ formatViews(video.views) }}
                </span>
                <span class="likes">
                  <el-icon><Star /></el-icon>
                  {{ video.likes }}
                </span>
              </div>
              <div class="meta-right">
                <span class="date">{{ formatDate(video.created_at) }}</span>
              </div>
            </div>
            <div class="video-actions" v-if="video.status === 'uploaded'">
              <el-button size="small" @click.stop="editVideo(video)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="danger" @click.stop="deleteVideo(video)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredVideos.length === 0" class="empty-state">
        <el-empty description="暂无视频内容">
          <el-button type="primary" @click="goToUpload">
            <el-icon><Upload /></el-icon>
            上传视频
          </el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElIcon, ElSelect, ElOption, ElButton, ElButtonGroup, ElEmpty, ElMessage } from 'element-plus'
import { 
  VideoPlay, Upload, Star, View, Grid, List, 
  CaretRight, Edit, Delete 
} from '@element-plus/icons-vue'
import api from '@/utils/axios'

const router = useRouter()

// 响应式数据
const selectedType = ref('all')
const sortBy = ref('newest')
const viewMode = ref('grid')
const loading = ref(false)

// 视频数据
const uploadedVideos = ref([])
const likedVideos = ref([])

// 计算属性
const filteredVideos = computed(() => {
  let videos = []
  
  if (selectedType.value === 'all') {
    videos = [...uploadedVideos.value, ...likedVideos.value]
  } else if (selectedType.value === 'uploaded') {
    videos = uploadedVideos.value
  } else if (selectedType.value === 'liked') {
    videos = likedVideos.value
  }
  
  // 排序
  return videos.sort((a, b) => {
    switch (sortBy.value) {
      case 'newest':
        return new Date(b.created_at) - new Date(a.created_at)
      case 'views':
        return b.views - a.views
      case 'likes':
        return b.likes - a.likes
      case 'title':
        return a.title.localeCompare(b.title)
      default:
        return 0
    }
  })
})

const totalViews = computed(() => {
  return uploadedVideos.value.reduce((sum, video) => sum + (video.views || 0), 0)
})

const totalLikes = computed(() => {
  return uploadedVideos.value.reduce((sum, video) => sum + (video.likes || 0), 0)
})

// 方法
const formatViews = (views) => {
  if (views >= 10000) {
    return (views / 10000).toFixed(1) + '万'
  }
  return views.toString()
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const goToDetail = (videoId) => {
  router.push(`/detail/${videoId}`)
}

const goToUpload = () => {
  router.push('/upload')
}

const getStatusText = (status) => {
  const statusMap = {
    'published': '已发布',
    'draft': '草稿',
    'processing': '处理中',
    'failed': '失败',
    'liked': '已点赞'
  }
  return statusMap[status] || '未知'
}

const editVideo = (video) => {
  console.log('编辑视频:', video)
  // 实现编辑功能
}

const deleteVideo = async (video) => {
  try {
    await api.delete(`/videos/${video.id}`)
    
    const index = uploadedVideos.value.findIndex(v => v.id === video.id)
    if (index > -1) {
      uploadedVideos.value.splice(index, 1)
      ElMessage.success('视频删除成功')
    }
  } catch (error) {
    console.error('删除视频失败:', error)
    ElMessage.error('删除视频失败')
  }
}

// 加载上传的视频
const loadUploadedVideos = async () => {
  try {
    loading.value = true
    const response = await api.get('/user/videos')
    if (response.success) {
      uploadedVideos.value = response.data
    }
  } catch (error) {
    console.error('加载上传视频失败:', error)
    // 使用示例数据
    uploadedVideos.value = [
      {
        id: 1,
        title: '复仇者联盟：终局之战',
        description: '漫威超级英雄的史诗级终章',
        thumbnail: '/images/videos/video1.jpg',
        duration: '03:01:00',
        views: 1250000,
        likes: 89000,
        status: 'published',
        created_at: new Date(Date.now() - 1000 * 60 * 60 * 24 * 7)
      },
      {
        id: 2,
        title: '权力的游戏 第八季',
        description: '史诗奇幻剧集的最终季',
        thumbnail: '/images/videos/video2.jpg',
        duration: '01:20:00',
        views: 980000,
        likes: 67000,
        status: 'published',
        created_at: new Date(Date.now() - 1000 * 60 * 60 * 24 * 5)
      }
    ]
  } finally {
    loading.value = false
  }
}

// 加载点赞的视频
const loadLikedVideos = async () => {
  try {
    const response = await api.get('/user/liked-videos')
    if (response.success) {
      likedVideos.value = response.data
    }
  } catch (error) {
    console.error('加载点赞视频失败:', error)
    // 使用示例数据
    likedVideos.value = [
      {
        id: 3,
        title: '精彩影视剧集',
        description: '精选影视内容推荐',
        thumbnail: '/images/videos/微信图片_20251027113113.jpg',
        duration: '01:45:00',
        views: 320000,
        likes: 25000,
        status: 'liked',
        created_at: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3)
      },
      {
        id: 4,
        title: '推荐视频1',
        description: '热门推荐内容',
        thumbnail: '/images/videos/微信图片_20251027113117.jpg',
        duration: '01:20:00',
        views: 280000,
        likes: 18000,
        status: 'liked',
        created_at: new Date(Date.now() - 1000 * 60 * 60 * 24 * 1)
      }
    ]
  }
}

onMounted(() => {
  loadUploadedVideos()
  loadLikedVideos()
})
</script>

<style scoped>
.my-videos-page {
  min-height: 100vh;
  background: #f9fafb;
}

.page-header {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  padding: 60px 0;
  color: white;
  text-align: center;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  font-size: 2.5rem;
  margin: 0 0 10px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.title-icon {
  font-size: 2.5rem;
}

.page-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.stats-section {
  background: white;
  padding: 40px 0;
  border-bottom: 1px solid #e5e7eb;
}

.stats-grid {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: #f8fafc;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  background: #e2e8f0;
  transform: translateY(-2px);
}

.stat-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 1.8rem;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 0.9rem;
  color: #6b7280;
}

.filter-section {
  background: white;
  padding: 30px 0;
  border-bottom: 1px solid #e5e7eb;
}

.filter-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
}

.content-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.videos-container.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.videos-container.list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.videos-container.list .video-card {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 16px;
}

.videos-container.list .video-thumbnail {
  width: 200px;
  height: 120px;
  flex-shrink: 0;
}

.video-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.video-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.video-thumbnail {
  position: relative;
  width: 100%;
  height: 180px;
  overflow: hidden;
}

.video-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.video-card:hover .video-overlay {
  opacity: 1;
}

.play-icon {
  font-size: 48px;
  color: white;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.video-status {
  position: absolute;
  top: 8px;
  left: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.video-status.published {
  background: #10b981;
  color: white;
}

.video-status.draft {
  background: #f59e0b;
  color: white;
}

.video-status.processing {
  background: #3b82f6;
  color: white;
}

.video-status.failed {
  background: #ef4444;
  color: white;
}

.video-status.liked {
  background: #ec4899;
  color: white;
}

.video-info {
  padding: 20px;
}

.video-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.video-description {
  font-size: 0.9rem;
  color: #6b7280;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.meta-left {
  display: flex;
  gap: 16px;
}

.meta-left span {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 0.85rem;
  color: #9ca3af;
}

.meta-right .date {
  font-size: 0.85rem;
  color: #9ca3af;
}

.video-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-title {
    font-size: 2rem;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .filter-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .videos-container.grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
  
  .videos-container.list .video-card {
    flex-direction: column;
  }
  
  .videos-container.list .video-thumbnail {
    width: 100%;
    height: 160px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 1.5rem;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .videos-container.grid {
    grid-template-columns: 1fr;
  }
}
</style>